<template>
  <div class="app-container">
    <el-card class="answer-sheet-wrapper">
      <template #header>
        <div class="card-header">
          <span>{{ form.paperName }}</span>
        </div>
      </template>
      <div>
        <span>学科：</span>{{ form.subjectName }}<span></span>
        <span style="margin-left: 16px">时长：</span
        ><span>{{ form.duration }}分</span>
      </div>
      <el-divider />
      <div>
        剩余时间
        <CountDown
          ref="countDownRef"
          :saveTime="form.countTime"
          @countdownFinished="countdownFinished"
        />
      </div>
      <el-divider />
      <div style="text-align: center">
        <el-button type="primary" plain @click="submitTest"
          >提交试卷
        </el-button>
      </div>
    </el-card>
    <el-row :gutter="20">
      <el-col :span="19" :offset="5">
        <el-card
          v-for="item in form.title"
          :key="item.id"
          class="test-title-wrapper"
        >
          <template #header>
            <div class="card-header">
              <span>{{ item.title }}</span>
            </div>
          </template>
          <el-row
            :gutter="20"
            v-for="(it, ix) in item.questionInfoList"
            :key="it.id"
            style="display: flex; align-items: center"
          >
            <el-col :xl="1" :lg="1" :md="1" :sm="1" :xs="1">
              <span>{{ ix + 1 }}.</span>
            </el-col>
            <el-col :xl="23" :lg="23" :md="23" :sm="23" :xs="23">
              <span v-html="it.content"></span>
            </el-col>
            <el-divider />
            <template v-if="it.topicId == 1">
              <el-radio-group v-model="it.answer" style="width: 100%">
                <el-col
                  :offset="1"
                  :xl="23"
                  :lg="23"
                  :md="23"
                  :sm="23"
                  :xs="23"
                  v-for="ele in JSON.parse(it.items)"
                  :key="ele.pre"
                  style="margin-top: 10px"
                >
                  <el-radio :label="ele.pre">
                    <span style="margin-right: 16px">{{ ele.pre }}:</span>
                    {{ ele.content }}</el-radio
                  >
                </el-col>
              </el-radio-group>
            </template>
            <template v-if="it.topicId == 2">
              <el-checkbox-group v-model="it.mutiAnswer" style="width: 100%">
                <el-col
                  :offset="1"
                  :xl="23"
                  :lg="23"
                  :md="23"
                  :sm="23"
                  :xs="23"
                  v-for="ele in JSON.parse(it.items)"
                  :key="ele.pre"
                  style="margin-top: 10px"
                >
                  <el-checkbox :label="ele.pre">
                    <span style="margin-right: 16px">{{ ele.pre }}:</span>
                    {{ ele.content }}</el-checkbox
                  >
                </el-col>
              </el-checkbox-group>
            </template>
            <template v-if="it.topicId == 3">
              <el-radio-group v-model="it.answer" style="width: 100%">
                <el-col
                  :offset="1"
                  :xl="23"
                  :lg="23"
                  :md="23"
                  :sm="23"
                  :xs="23"
                  v-for="ele in JSON.parse(it.items)"
                  :key="ele.pre"
                  style="margin-top: 10px"
                >
                  <el-radio :label="ele.pre"> {{ ele.pre }}</el-radio>
                </el-col>
              </el-radio-group>
            </template>
            <template v-if="it.topicId == 5">
              <el-col
                :offset="1"
                :xl="23"
                :lg="23"
                :md="23"
                :sm="23"
                :xs="23"
                v-for="ele in it.gapAnswer"
                :key="ele.pre"
                style="margin-top: 10px"
              >
                <el-input
                  placeholder="请输入内容"
                  v-model="ele.content"
                  style="margin-bottom: 10px"
                >
                  <template #prepend>{{ ele.pre }}</template>
                </el-input>
              </el-col>
            </template>
            <template v-if="it.topicId == 6">
              <el-col
                :offset="1"
                :xl="23"
                :lg="23"
                :md="23"
                :sm="23"
                :xs="23"
                style="margin-top: 10px"
              >
                <el-input
                  type="textarea"
                  placeholder="请输入内容"
                  v-model="it.answer"
                  maxlength="100"
                  show-word-limit
                >
                </el-input>
              </el-col>
            </template>
            <template v-if="it.topicId == 7">
              <el-col
                :offset="1"
                :xl="23"
                :lg="23"
                :md="23"
                :sm="23"
                :xs="23"
                style="margin-top: 10px"
              >
                <AnswerEditor v-model:modelValue="it.answer" />
              </el-col>
            </template>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="TestDetail">
import { getSchoolClassList } from "@/api/core/class";
import { getSubjectList } from "@/api/core/subject";
import { getQuestionList } from "@/api/core/question";
import {
  addTestPaper,
  editTestPaper,
  getTestPaperDetail,
} from "@/api/core/testPaper";
import { stuAnswerSubmit } from "@/api/core/test";

import {
  getCurrentInstance,
  reactive,
  ref,
  toRefs,
  watch,
  computed,
} from "vue";
import { parseTime } from "@/utils/ruoyi";
import useUserStore from "@/store/modules/user";
const topicTypeList = ref([
  { id: 1, label: "单选" },
  { id: 2, label: "多选" },
  { id: 3, label: "判断" },
  { id: 5, label: "填空" },
  { id: 6, label: "简答" },
  { id: 7, label: "编程题" },
]);
const { proxy } = getCurrentInstance();
const classList = ref([]);
const subjectOptions = ref([]);
const questionList = ref([]);
const selectQuesList = ref([]);
const total = ref(0);
const open = ref(false);
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const data = reactive({
  form: {
    id: null,
    title: [
      {
        value: "",
        id: 1,
        list: [],
      },
    ],
    subId: "",
    subjectName: "",
    classIdList: [],
    paperName: "",
    duration: "",
    countTime: 0,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    topicId: undefined,
    content: undefined,
  },
  currentRow: {},
  rules: {
    subId: [{ required: true, trigger: "blur", message: "学科不能为空" }],
    classIdList: [
      { required: true, trigger: "change", message: "参试班级不能为空" },
    ],
    paperName: [
      {
        required: true,
        trigger: ["blur"],
        message: "试卷名称能为空",
      },
    ],
    duration: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: "建议时长不能为空",
      },
    ],
  },
});
const { queryParams, form, rules, currentRow } = toRefs(data);

/** 查询班级列表 */
function getClassList() {
  getSchoolClassList().then((res) => {
    classList.value = res.rows;
  });
}
// 查询学科列表
function getSubList() {
  getSubjectList().then((res) => {
    subjectOptions.value = res.rows;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getQuestionTable();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 选择条数  */
function handleSelectionChange(selection) {
  selectQuesList.value = selection;
}
function handleStudentChange(selection) {
  studentSelect.value = selection.map((item) => item.userId);
}

/** 重置操作表单 */
function reset() {
  form.value = {
    id: null,
    className: "",
    classCode: "",
  };
  proxy.resetForm("testPaperForm");
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

// 添加标题
function addTitle() {
  form.value.title.push({
    value: "",
    id: form.value.title.length + 1,
    list: [],
  });
}
// 删除标题
function RemoveTitle(item) {
  let index = form.value.title.indexOf(item);
  if (index !== -1) {
    form.value.title.splice(index, 1);
  }
}
/** 删除按钮操作 */
function handleDeleteQuestion(row, child) {
  let index = row.list.indexOf(child);
  if (index !== -1) {
    row.list.splice(index, 1);
  }
}
// 返回试卷列表
function handleBack() {
  const obj = { path: "/test/detail" };
  proxy.$tab.closeOpenPage(obj);
  router.push({ path: "/test/testList" });
}
function getQuestionTable() {
  getQuestionList({ subjectId: form.value.subId }).then((res) => {
    questionList.value = res.rows;
    total.value = res.total;
  });
}
// 添加题目
function addQuestion(row) {
  currentRow.value = row;
  if (form.value.subId) {
    open.value = true;
    getQuestionTable();
  } else {
    proxy.$modal.msgWarning("请选择学科");
  }
}
function subjectChange() {
  form.value.title = [
    {
      value: "",
      id: 1,
      list: [],
    },
  ];
  form.value.paperName = "";
}
/** 添加题目确认 */
function selectQuestion() {
  open.value = false;
  let findObj = form.value.title.find((item) => item.id == currentRow.value.id);
  console.log("dafafdaf", findObj);
  findObj.list = findObj.list.concat(selectQuesList.value);
  console.log(form.value);
}
// 提交试卷
function submitTest() {
  let paramAnswer = form.value.title.map((item) => {
    let arr = item.questionInfoList.map((it) => {
      let returnObj = { answer: "A,B", id: it.id };
      if (it.topicId == 5) {
        returnObj.answer = JSON.stringify(it.gapAnswer);
      } else if (it.topicId == 2) {
        returnObj.answer = it.mutiAnswer.toString();
      } else {
        returnObj.answer = it.answer;
      }
      return returnObj;
    });
    return arr;
  });
  console.log(paramAnswer.flat());
  proxy.$modal
    .confirm("是否提交试卷？")
    .then(() => {
      let paramObj = {
        examPaperId: route.query.paperId,
        studentId: userStore.userId,
        anwser: JSON.stringify(paramAnswer.flat()),
      };
      stuAnswerSubmit(paramObj).then((res) => {
        if (res.code == 200) {
          proxy.$refs["countDownRef"].clearTime();
          handleBack();
          proxy.$modal.msgSuccess("提交成功");
        }
      });
    })
    .catch(() => {});
}
function countdownFinished() {}
// 监听路由变化
watch(
  () => route.query,
  (newValue, oldValue) => {
    if (newValue.paperId) {
      getTestPaperDetail(newValue.paperId).then((res) => {
        console.log("打印试卷详情", res);
        form.value.paperName = res.data.paperName;
        form.value.duration = res.data.duration;
        form.value.countTime = form.value.duration * 60;
        nextTick(() => {
          proxy.$refs["countDownRef"].init();
        });

        form.value.subjectName = res.data.subjectName;
        form.value.title = res.data.titles.map((item) => {
          // 增加作答的字段
          item.questionInfoList = item.questionInfoList.map((it) => {
            return {
              ...it,
              // 单选、判断、简答、编程体题
              answer: "",
              // 多选得
              mutiAnswer: [],
              // 填空得
              gapAnswer: JSON.parse(it.items).map((ele) => {
                return {
                  pre: ele.pre,
                  content: "",
                };
              }),
            };
          });

          return item;
        });
        form.value.id = res.data.id;
      });
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
.answer-sheet-wrapper {
  width: 17%;
  top: 104px;
  position: fixed;
  z-index: 999;
}
.card-header {
  font-size: 18px;
  font-weight: 500;
}
.test-title-wrapper {
  margin-bottom: 16px;

  &:last-child {
    margin-bottom: 0;
  }
}
</style>
